package de.hbrs.selectionengine.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.Stateless;

public class IOHelper {

	private static final Logger logger = Logger.getLogger("Logging");

	public void createFolder(String path) {

		if (new File(path).mkdir() == false) {
			logger.log(Level.INFO, "Ordner " + path
					+ " existiert bereits.");
		}
	}

	public static void createFolders(String foldersPath)
			throws CouldNotCreateFolderException {

		if (new File(foldersPath).exists()) {
			logger.log(Level.INFO, "Ordner " + foldersPath
					+ " existiert bereits.");
			return;
		}

		if (new File(foldersPath).mkdirs() == false) {
			throw new CouldNotCreateFolderException(
					"Folders could not be created!");
		}
	}

	public static void callCommandLineTool(String[] args) throws IOException,
			InterruptedException {

		System.out.println(Arrays.toString(args));

		try {
			String line;
			Process p = Runtime.getRuntime().exec(args);
			BufferedReader bri = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			BufferedReader bre = new BufferedReader(new InputStreamReader(
					p.getErrorStream()));
			while ((line = bri.readLine()) != null) {
				System.out.println(line);
			}
			bri.close();
			while ((line = bre.readLine()) != null) {
				System.out.println(line);
			}
			bre.close();
			p.waitFor();
			System.out.println("Done.");
		} catch (Exception err) {
			err.printStackTrace();
		}
	}

	public static ArrayList<File> readAllFilesFromFolder(String path) {

		ArrayList<File> files = new ArrayList<File>();
		File folder = new File(path);
		File[] listOfFiles = folder.listFiles();

		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				System.out.println("File " + listOfFiles[i].getName());
				files.add(listOfFiles[i]);

			} else if (listOfFiles[i].isDirectory()) {
				System.out.println("Directory " + listOfFiles[i].getName());
			}
		}
		return files;
	}
}

class CouldNotCreateFolderException extends Exception {

	public CouldNotCreateFolderException() {
	}

	public CouldNotCreateFolderException(String msg) {
		super(msg);
	}
}
